import qiniu from 'qiniu';
import moment from 'moment';
import {randomDigits} from '../../../util';
import log from '../../../log';


//需要填写你的 Access Key 和 Secret Key
qiniu.conf.ACCESS_KEY = 'HEdAg1cviMignaXFDWhy8TPW-jsjUYdD2O-fRPq3';
qiniu.conf.SECRET_KEY = 'PohsDUYfC1QZvpAY2sKtCK6bwzrilNDkBe_jROHh';


//构建上传策略函数
function uptoken(bucket, key) {
    const putPolicy = new qiniu.rs.PutPolicy(`${bucket}:${key}`);
    return putPolicy.token();
}

//构造上传函数
export default function upload(ctx) {
    const { files: { file }, fields: { productId } = {} } = ctx.request.body;
    if (!file || !file.size) {
        throw '文件为空!';
    }
    //console.log('xxxxxxxxx file:', file);
    const {localFile} = file.path;
    const extra = new qiniu.io.PutExtra();
    //要上传的空间
    const bucket = 'felixzxk';
    //上传到七牛后保存的文件名
    const key = `${moment().format('YYYYMMDDHHmmss')}${randomDigits(4)}/${file.name.substr(file.indexOf('.'))}`;
    log.info('xxxxxxxxx productId:', productId);
    //console.log('xxxxxxxxx key:', key);
    //生成上传 Token
    const token = uptoken(bucket, key);
    qiniu.io.putFile(token, key, localFile, extra, (err, ret) => {
        if (!err) {
            // 上传成功， 处理返回值
            log.info(ret.hash, ret.key, ret.persistentId);
        } else {
            // 上传失败， 处理返回代码
            log.error(err);
        }
    });
}
